﻿using HardToolApp.Model;
using HardToolApp.View;
using HardToolApp.ViewModel;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Shapes;
using static HardToolApp.Model.Communicate;
using static HardToolApp.ViewModel.USBInfoVM;

namespace HardToolApp.Tool
{
    internal class Presupposition
    {


        /// <summary>
        /// 检查是否需要新建预设
        /// </summary>
        /// <returns></returns>
        public static ObservableCollection<CmdsModel> NeedNewPresupposition()
        {
            ObservableCollection < CmdsModel> cmds = new ObservableCollection<CmdsModel>();
            if (!Directory.Exists("./cmds"))
            {
                Directory.CreateDirectory("./cmds");
            }
            if (!Directory.Exists("./cmds/Files"))
            {
                Directory.CreateDirectory("./cmds/Files");
            }
            if (!File.Exists("./cmds/index.json"))// 存在直接返回
            {
                PreSet();
            }


            if (!Directory.Exists("./cmds/Lua"))
            {
                Directory.CreateDirectory("./cmds/Lua");
            }
            Assembly assembly = Assembly.GetExecutingAssembly();

            var type = from t in assembly.GetManifestResourceNames()
                       where  t.Contains("HardToolApp.Lua")
                       select t;

            foreach (string t in type.ToList())
            {
                string FileName = "./cmds/Lua/" + t.Substring("HardToolApp.Lua.".Length);
                if (!File.Exists(FileName))
                {
                    using (Stream stream = assembly.GetManifestResourceStream(t))
                    {
                        byte[] buffer = new byte[stream.Length];
                        stream.Read(buffer, 0, buffer.Length);
                        stream.Seek(0, SeekOrigin.Begin);
                        using (FileStream fs = new FileStream(FileName, FileMode.Create))
                            fs.Write(buffer, 0, buffer.Length);
                    }
                }
            }


            try
            {
                cmds = new ObservableCollection<CmdsModel>(JsonConvert.DeserializeObject<IList<CmdsModel>>(File.ReadAllText("./cmds/index.json")));
            }
            catch
            {

            }

            return cmds;
        }

        /// <summary>
        /// 保存预设
        /// </summary>
        /// <param name="orders"></param>
        /// <param name="cmds"></param>
        /// <param name="Name"></param>
        public static void SaveCmds(ObservableCollection<OrderModel> orders, ObservableCollection<CmdsModel> cmds, string Name)
        {
            
            if (!Directory.Exists("./cmds"))
            {
                Directory.CreateDirectory("./cmds");
            }
            if (!Directory.Exists("./cmds/Files"))
            {
                Directory.CreateDirectory("./cmds/Files");
            }
            string path = "./cmds/Files/" + Name + ".json";
            string info = JsonConvert.SerializeObject(orders);
            if (File.Exists(path))
            {
                if (HandyControl.Controls.MessageBox.Show("已经存在文件，是否覆盖", button: MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    for (int i = 0; i < cmds.Count; i++)
                    {
                        if (cmds[i].Name.Equals(Name))
                        {
                            cmds[i].Path = path;
                            break;
                        }
                    }
                    File.WriteAllText(path, info);
                }
            }
            else
            {
                cmds.Add(new CmdsModel() { Name = Name, Path = path });
                File.WriteAllText(path, info);
                File.WriteAllText("./cmds/index.json", JsonConvert.SerializeObject(cmds));
            }
        }

        /// <summary>
        /// 从文件中载入预设命令
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static ObservableCollection<OrderModel> Load(string path)
        {
            var setting = new JsonSerializerSettings
            {
                Converters = new List<JsonConverter>
                    {
                        new JsonOrderVM()
                    }
            };
            return new ObservableCollection<OrderModel>(JsonConvert.DeserializeObject<IList<OrderModel>>(File.ReadAllText(path), setting));
        }

        /// <summary>
        /// 删除命令
        /// </summary>
        /// <param name="p"></param>
        /// <param name="cmds"></param>
        public static void Delete(CmdsModel p, ObservableCollection<CmdsModel> cmds)
        {
            File.Delete(p.Path);
            cmds.Remove(p);
            File.WriteAllText("./cmds/index.json", JsonConvert.SerializeObject(cmds));
        }

        private static void PreCmdCopy(string name)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            string resourceName = assembly.GetName().Name.ToString() + ".PreCmd." + name+".json";
            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            {
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                stream.Seek(0, SeekOrigin.Begin);
                using (FileStream fs = new FileStream("./cmds/Files/"+name+".json", FileMode.Create))
                    fs.Write(buffer, 0, buffer.Length);
            }
        }

        /// <summary>
        /// 设置预设命令
        /// </summary>
        private static void PreSet()
        {

            //string sDb = AppDomain.CurrentDomain.BaseDirectory + "index.json";
            Assembly assembly = Assembly.GetExecutingAssembly();
            string resourceName = assembly.GetName().Name.ToString() + ".PreCmd.index.json";
            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
            {
                byte[] buffer = new byte[stream.Length];
                stream.Read(buffer, 0, buffer.Length);
                stream.Seek(0, SeekOrigin.Begin);
                using (FileStream fs = new FileStream("./cmds/index.json", FileMode.Create))
                    fs.Write(buffer, 0, buffer.Length);
            }
            PreCmdCopy("ST7789V");
            PreCmdCopy("IIC12864");
            PreCmdCopy("SPI12864");
        }
    }
}
